CREATE TABLE [dbo].[session_id_usuario](
	[session_id] [int] NOT NULL,
	[id_usuario] [int] NOT NULL,
 CONSTRAINT [pk_session_id] PRIMARY KEY CLUSTERED 
(
	[session_id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO


/****** Object:  StoredProcedure [dbo].[set_current_user]    Script Date: 08/06/2010 01:07:26 ******/

CREATE PROCEDURE [dbo].[set_current_user]
	@id_usuario int
AS 
	
BEGIN TRANSACTION
	DECLARE @exists int;

	SET @exists = ( SELECT id_usuario
					FROM   session_id_usuario
					WHERE  session_id = @@SPID)

	IF (@exists > 0)
		UPDATE session_id_usuario 
		SET id_usuario = @id_usuario
		WHERE session_id = @@SPID
	ELSE
		INSERT INTO session_id_usuario (session_id, id_usuario)
		VALUES ( @@SPID, @id_usuario )

COMMIT TRANSACTION


GO


CREATE FUNCTION [dbo].[get_current_user]() RETURNS INT
AS
BEGIN
	DECLARE @id_usuario INT

	SET @id_usuario = (SELECT TOP 1 u.id_usuario
						FROM session_id_usuario AS s 
						INNER JOIN usuarios AS u ON (s.id_usuario = u.id_usuario )
						WHERE s.session_id = @@SPID)

	RETURN @id_usuario 
END


GO

